import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyPage.dart';
import 'package:hitutor/Widget/WordsPLayer.dart';

import 'WordsTestDone.dart';

class WordsShowCard extends StatefulWidget {
  dynamic data;

  WordsShowCard(this.data);

  @override
  State<StatefulWidget> createState() {
    return _WordsShowCard();
  }
}

class _WordsShowCard extends State<WordsShowCard> {
  bool showAnswer = false;
  static int sec = 0;
  List<dynamic> questions = [];
  int currentPos = 0;

  nextClick(String userAnswer) {
    bool isRight = userAnswer.isNotEmpty;
    HttpGo(context).post("/HiNote/AnswerVocabularyQuiz", {
      "vocabularyQuizId":widget.data["vocabularyQuizId"],
      "vocabularyId": questions[currentPos]["questionId"],
      "answer": userAnswer,
      "answerTotalSecond": sec,
      "isRight": isRight
    }, (data) {
      if (!isRight) {
        questions.add(questions[currentPos]);
      }
      if (currentPos == questions.length - 1) {
        PageUtil().openReplace(context, WordsTestDone());
        return;
      }
      currentPos += 1;
      showAnswer = false;
      sec = 0;
      setState(() {});
    }, (code, error) => showToast(error));
  }

  late Timer _timer;

  @override
  void initState() {
    questions = widget.data["questions"];
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        sec += 1;
        print("sec:${sec}");
      });
    });
    super.initState();
  }

  @override
  void dispose() {
    if (_timer.isActive) {
      _timer.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double progress = (currentPos + 1) / questions.length;
    print("${currentPos + 1} / ${questions.length}");
    dynamic question = questions[currentPos];
    String answer = "";
    for (var item in question["answers"]) {
      if (item["isAnswer"]) {
        answer = item["answerContent"];
      }
    }
    return MyPage(
        "閃示卡",
        Container(
            padding: EdgeInsets.fromLTRB(12, 32, 12, 12),
            child: Column(children: [
              GestureDetector(
                onTap: () {
                  showAnswer = true;
                  setState(() {});
                },
                child: Container(
                    height: 120,
                    width: double.infinity,
                    alignment: Alignment.center,
                    decoration: showAnswer
                        ? BoxDecoration(color: Color(0xfffffffff), borderRadius: BorderRadius.vertical(top: Radius.circular(10)))
                        : Global.getWhiteBg(10),
                    child: Text("${question["questionContent"]}",
                        style: TextStyle(fontSize: 18, color: MyColor.C7D, fontWeight: FontWeight.bold))),
                // child: type == E2C
                //     ? WordsPlayer(words: "winter", soundUrl: Global.winterUrl, vertical: true)
                //     : Text("冬天", style: TextStyle(fontSize: 18, color: MyColor.C7D, fontWeight: FontWeight.bold))),
              ),
              Visibility(
                  visible: showAnswer,
                  child: Column(children: [
                    Container(
                        margin: EdgeInsets.only(bottom: 48),
                        padding: EdgeInsets.all(20),
                        width: double.infinity,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(color: MyColor.Orange, borderRadius: BorderRadius.vertical(bottom: Radius.circular(10))),
                        // child: type == E2C
                        //     ? Text("冬天", style: TextStyle(fontSize: 18, color: MyColor.White, fontWeight: FontWeight.bold))
                        //     : WordsPlayer(words: "winter", soundUrl: Global.winterUrl, vertical: true, white: true),
                        child: Text("$answer", style: TextStyle(fontSize: 18, color: MyColor.White, fontWeight: FontWeight.bold))),
                    Text("你答對了嗎?", style: TextStyle(fontSize: 13, color: MyColor.C7D)),
                    Container(height: 16),
                    Row(mainAxisSize: MainAxisSize.min, children: [
                      LocalImage("cross-circle.png", width: 48, padding: EdgeInsets.all(4), onTap: () {
                        nextClick("");
                      }),
                      LocalImage("check-circle.png", width: 48, padding: EdgeInsets.all(4), onTap: () {
                        nextClick(answer);
                      })
                    ])
                  ])),
              Expanded(child: Container()),
              Visibility(visible: !showAnswer, child: Text("點擊卡片看解釋", style: TextStyle(fontSize: 14, color: MyColor.C7D))),
              Container(height: 24),
              LinearProgressIndicator(value: progress, color: MyColor.Orange, backgroundColor: Color(0xffffeade))
            ])),
        bgColor: MyColor.F8);
  }
}
